package com.renwei.yunlong.activity.me;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.Company;
import com.renwei.yunlong.bean.FriendEnterpriseBean;
import com.renwei.yunlong.bean.OtherCompanyBean;
import com.renwei.yunlong.event.SaveImg2GallaryEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.global.IntentKey;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.qrcode.SimpleCaptureActivity;
import com.renwei.yunlong.service.ImageSaveService;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.PermissionUtil;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import github.opensource.dialog.prompt.PromptButton;
import github.opensource.dialog.prompt.PromptButtonListener;
import github.opensource.dialog.prompt.PromptDialog;

/**
 * 企业二维码--页面
 * <p>
 * Created by Administrator on 2017/8/28.
 */

public class QRCodeActivity extends BaseActivity implements View.OnClickListener, View.OnLongClickListener, HttpTaskListener, RationaleListener, PermissionListener {


    private static final int REQUEST_QR_CODE = 1;
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_edit)
    TextView tvEdit;
    @Bind(R.id.iv_cont)
    ImageView ivCont;
    @Bind(R.id.iv_edit)
    ImageView ivEdit;
    @Bind(R.id.iv_contacts)
    ImageView ivContacts;
    @Bind(R.id.iv_more)
    ImageView ivMore;
    @Bind(R.id.iv_scroll)
    ImageView ivScroll;
    @Bind(R.id.top_bar)
    RelativeLayout topBar;
    @Bind(R.id.tv_company_name)
    TextView tvCompanyName;
    @Bind(R.id.tv_company_code)
    TextView tvCompanyCode;
    @Bind(R.id.iv_code_img)
    ImageView ivCodeImg;
    private String companyCode;
    private String qrImageCodePath;
    private FriendEnterpriseBean infoBean;
    private PromptDialog promptDialog;
    private Intent serviceIntent;


    public static void openActivity(Context context, String companyCode) {
        Intent intent = new Intent(context, QRCodeActivity.class);
        intent.putExtra("companyCode", companyCode);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qrcode);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        companyCode = getIntent().getStringExtra("companyCode") == null ? "" : getIntent().getStringExtra("companyCode");
        qrImageCodePath = Api.$().MiDDLE_URL + "qrcode/" + companyCode + "/" + companyCode + ".gif";
        initData();
    }

    private void initData() {
        ivBack.setVisibility(View.VISIBLE);
        ivMore.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(this);
        ivMore.setOnClickListener(this);
        tvTitle.setText("企业二维码");
        tvEdit.setOnClickListener(this);
        LogUtil.e("qrImageCodePath：" + qrImageCodePath);
        Glide.with(this).load(qrImageCodePath).error(R.mipmap.load_err).into(ivCodeImg);
        ivCodeImg.setScaleType(ImageView.ScaleType.FIT_XY);
        ServiceRequestManager.getManager().QueryFirendCompany(this, companyCode, this);
        promptDialog = new PromptDialog(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_more:
                PromptButton cancle = new PromptButton("取消", null);
                promptDialog.showAlertSheet("", true, cancle,
                        new PromptButton("保存到相册", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                //读取权限
                                PermissionUtil.checkSinglePermission(QRCodeActivity.this, QRCodeActivity.this, QRCodeActivity.this, Permission.STORAGE);
                            }
                        }), new PromptButton("扫描二维码", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                SimpleCaptureActivity.openSannerActivity(QRCodeActivity.this, IntentKey.QR_SANNER);
                            }
                        }));
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onLongClick(View view) {

        return false;
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 879:
                infoBean = new Gson().fromJson(result, FriendEnterpriseBean.class);
                if (infoBean != null && infoBean.getMessage() != null && infoBean.getMessage().getCode() == 200) {
                    if (null != infoBean.getRows()) {
                        FriendEnterpriseBean.RowsBean company = infoBean.getRows();
                        tvCompanyName.setText(StringUtils.value(company.getCompanyName()));
                        tvCompanyCode.setText(StringUtils.value(company.getCompanyCode()));
                    }
                } else {
                    showCenterInfoMsg("数据错误");
                }
                break;
            case 880://扫描二维码查询相关信息
                OtherCompanyBean companyBean = new Gson().fromJson(result, OtherCompanyBean.class);
                if (companyBean != null) {
                    if (companyBean.getCompany() != null) {
                        doCompareCompany(companyBean.getCompany());
                    } else {
                        showCenterInfoMsg("没有查询到相关企业信息");
                    }
                } else {
                    showCenterInfoMsg("没有查询到相关企业信息");
                }
                break;
            default:

                break;

        }
    }

    //比较企业信息
    public void doCompareCompany(Company company) {
        String flag = StringUtils.value(AppHelper.getMyCompanyInfo().getRows().getCheckFlag());
        if (!"2".equals(StringUtils.value(flag))) {
            showCenterInfoMsg("贵公司尚未认证,无法添加企业好友");
            return;
        }
        if (company != null) {
          //  showCenterInfoMsg("isBing:" + StringUtils.value(company.getIsBing()));
            String targetCompanyType = StringUtils.value(company.getType());
            if ("1".equals(companyType) && companyType.equals(targetCompanyType)) {
                showCenterInfoMsg("贵公司作为业主,只能邀请服务商成为好友企业");
                return;
            } else if ("2".equals(companyType)
                    && companyType.equals(targetCompanyType)) {
                showCenterInfoMsg("贵公司作为服务商,只能邀请业主成为好友企业");
                return;
            } else if (!"2".equals(company.getCheckFlag())) {
                showCenterInfoMsg("对方还未认证,不能发送邀请");
                return;
            } else if ("0".equals(StringUtils.value(company.getIsBing()))) {
                CompanyInfoActivity.OpenActivity(this, company, "");
                //不是企业好友打开信息页面
            } else {
                DisplayEnterpriseInfoActivity.OpenActivity(this, StringUtils.value(company.getCompanyCode()));
            }//是企业好友查看很多资料的企业详情
        }
    }

    @Override
    public void onException(int requestId, String code) {
    }


    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEvent(SaveImg2GallaryEvent event) {
        if (event.isSaveResult()) {
            showCenterSuccessMsg("保存成功");
        } else {
            showCenterInfoMsg("保存失败");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
        AndPermission.rationaleDialog(this, rationale).show();
    }

    @Override
    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
        if (AndPermission.hasAlwaysDeniedPermission(this, grantPermissions)) {
            // 第一种：用默认的提示语。
            serviceIntent = new Intent(QRCodeActivity.this, ImageSaveService.class);
            serviceIntent.putExtra("imagePath", qrImageCodePath);
            startService(serviceIntent);

        }

    }

    @Override
    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, PermissionUtil.SETTING_CODE).show();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PermissionUtil.SETTING_CODE:
                initData();
                break;
            case IntentKey.QR_SANNER:
                if (data != null && data.getStringExtra("result") != null) {
                    ServiceRequestManager manager = ServiceRequestManager.getManager();
                    String result = StringUtils.value(data.getStringExtra("result"));
                    HashMap<String, String> map = new HashMap<>();
                    map.put("isBingCompanyCode", StringUtils.value(getCompanyCode()));
                    map.put("companyCode", StringUtils.value(result));
                    manager.ScanCompanyQRcode(this, JsonMapUtil.mapToJson(map), this);
                }
                break;
                default:
                break;
        }
    }
}
